# -*- coding: utf-8 -*-
from fastapi import Request
from pydantic import BaseModel
from typing import List

from schemas.response_entity import JsonModel
from db.repository.attributes import (
    db_create_applicable_object, db_update_applicable_object, db_delete_applicable_object, db_get_all_applicable_objects,
    # KnowledgeType CRUD
    db_create_knowledge_type, db_update_knowledge_type, db_delete_knowledge_type, db_get_all_knowledge_types,
    # ApplicableArea CRUD
    db_create_applicable_area, db_update_applicable_area, db_delete_applicable_area, db_get_all_applicable_areas,
    # ElementClassification CRUD
    db_create_element_classification, db_update_element_classification, db_delete_element_classification, db_get_all_element_classifications,
    # AccidentType CRUD
    db_create_accident_type, db_update_accident_type, db_delete_accident_type, db_get_all_accident_types,
)


class SearchFileTypeEntity(BaseModel):
    search_types: List[str] = []


# Request/Response Models
class CreateAttributeEntity(BaseModel):
    type: str  # "applicable_object", "knowledge_type", "applicable_area", "element_classification", "accident_type"
    name: str


class UpdateAttributeEntity(BaseModel):
    type: str  # "applicable_object", "knowledge_type", "applicable_area", "element_classification", "accident_type"
    id: int
    name: str


class DeleteAttributeEntity(BaseModel):
    type: str  # "applicable_object", "knowledge_type", "applicable_area", "element_classification", "accident_type"
    id: int


# =========================== 通用CRUD接口 ================================

async def create_attribute(request: Request, payload: CreateAttributeEntity):
    """创建属性 - 支持所有4种模型类型"""
    mapping = {
        "applicable_object": db_create_applicable_object,
        "knowledge_type": db_create_knowledge_type,
        "applicable_area": db_create_applicable_area,
        "element_classification": db_create_element_classification,
        "accident_type": db_create_accident_type,
    }
    try:
        obj = mapping[payload.type](payload.name)
        if obj:
            return JsonModel(code=200, data=obj.to_json(), msg=f"{payload.type}创建成功").to_response()
        else:
            return JsonModel(code=400, data=None, msg=f"{payload.type}不存在").to_response()
    except Exception as e:
        return JsonModel(code=500, data=None, msg=f"创建失败: {str(e)}").to_response()


async def list_attributes(request: Request, payload: SearchFileTypeEntity):
    """查找属性 - 支持所有4种模型类型，可获取所有或根据ID获取"""
    user = request.state.user
    search_type_mapping = {}
    if not payload.search_types:
        payload.search_types = ["applicable_object", "knowledge_type", "applicable_area", "element_classification", "accident_type"]
    if "applicable_object" in payload.search_types:
        search_type_mapping["applicable_object"] = [i.to_json() for i in db_get_all_applicable_objects()]

    if "knowledge_type" in payload.search_types:
        search_type_mapping["knowledge_type"] = [i.to_json() for i in db_get_all_knowledge_types()]

    if "applicable_area" in payload.search_types:
        search_type_mapping["applicable_area"] = [i.to_json() for i in db_get_all_applicable_areas()]

    if "element_classification" in payload.search_types:
        search_type_mapping["element_classification"] = [i.to_json() for i in db_get_all_element_classifications()]

    if "accident_type" in payload.search_types:
        # accident_type 不属于文件属性集合，单独从 attributes 仓储获取
        ats = db_get_all_accident_types()
        search_type_mapping["accident_type"] = [a.to_json() for a in ats]

    return JsonModel(code=200, data=search_type_mapping, msg=f"success").to_response()


async def update_attribute(request: Request, payload: UpdateAttributeEntity):
    """更新属性 - 支持所有4种模型类型"""
    mapping = {
        "applicable_object": db_update_applicable_object,
        "knowledge_type": db_update_knowledge_type,
        "applicable_area": db_update_applicable_area,
        "element_classification": db_update_element_classification,
        "accident_type": db_update_accident_type,
    }
    try:
        obj = mapping[payload.type](payload.id, payload.name)
        if obj:
            return JsonModel(code=200, data=obj.to_json(), msg=f"{payload.type}更新成功").to_response()
        else:
            return JsonModel(code=400, data=None, msg=f"{payload.type}不存在").to_response()
    except Exception as e:
        return JsonModel(code=500, data=None, msg=f"更新失败: {str(e)}").to_response()


async def delete_attribute(request: Request, payload: DeleteAttributeEntity):
    """删除属性 - 支持所有4种模型类型"""
    mapping = {
        "applicable_object": db_delete_applicable_object,
        "knowledge_type": db_delete_knowledge_type,
        "applicable_area": db_delete_applicable_area,
        "element_classification": db_delete_element_classification,
        "accident_type": db_delete_accident_type,
    }
    try:
        success = mapping[payload.type](payload.id)
        if success:
            return JsonModel(code=200, data=None, msg=f"{payload.type}删除成功").to_response()
        else:
            return JsonModel(code=400, data=None, msg=f"{payload.type}不存在").to_response()
    except Exception as e:
        return JsonModel(code=500, data=None, msg=f"删除失败: {str(e)}").to_response()
